package com.autoglm.data.repository

import com.autoglm.data.local.dao.TaskDao
import com.autoglm.data.local.entity.TaskEntity
import com.autoglm.data.model.Task
import com.autoglm.data.model.TaskStatus
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.util.Date
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 任务仓库
 * 负责任务数据的本地存储和管理
 */
@Singleton
class TaskRepository @Inject constructor(
    private val taskDao: TaskDao
) {
    
    /**
     * 获取所有任务
     */
    fun getAllTasks(): Flow<List<Task>> {
        return taskDao.getAllTasks().map { entities ->
            entities.map { it.toTask() }
        }
    }
    
    /**
     * 根据ID获取任务
     */
    suspend fun getTaskById(taskId: String): Task? {
        return taskDao.getTaskById(taskId)?.toTask()
    }
    
    /**
     * 根据状态获取任务
     */
    fun getTasksByStatus(status: TaskStatus): Flow<List<Task>> {
        return taskDao.getTasksByStatus(status).map { entities ->
            entities.map { it.toTask() }
        }
    }
    
    /**
     * 根据多个状态获取任务
     */
    fun getTasksByStatuses(statuses: List<TaskStatus>): Flow<List<Task>> {
        return taskDao.getTasksByStatuses(statuses).map { entities ->
            entities.map { it.toTask() }
        }
    }
    
    /**
     * 搜索任务
     */
    fun searchTasks(query: String): Flow<List<Task>> {
        return taskDao.searchTasks(query).map { entities ->
            entities.map { it.toTask() }
        }
    }
    
    /**
     * 根据日期范围获取任务
     */
    fun getTasksByDateRange(startDate: Date, endDate: Date): Flow<List<Task>> {
        return taskDao.getTasksByDateRange(startDate, endDate).map { entities ->
            entities.map { it.toTask() }
        }
    }
    
    /**
     * 插入任务
     */
    suspend fun insertTask(task: Task) {
        taskDao.insertTask(task.toEntity())
    }
    
    /**
     * 插入多个任务
     */
    suspend fun insertTasks(tasks: List<Task>) {
        taskDao.insertTasks(tasks.map { it.toEntity() })
    }
    
    /**
     * 更新任务
     */
    suspend fun updateTask(task: Task) {
        taskDao.updateTask(task.toEntity())
    }
    
    /**
     * 删除任务
     */
    suspend fun deleteTask(task: Task) {
        taskDao.deleteTask(task.toEntity())
    }
    
    /**
     * 根据ID删除任务
     */
    suspend fun deleteTaskById(taskId: String) {
        taskDao.deleteTaskById(taskId)
    }
    
    /**
     * 根据状态删除任务
     */
    suspend fun deleteTasksByStatus(status: TaskStatus) {
        taskDao.deleteTasksByStatus(status)
    }
    
    /**
     * 删除旧任务
     */
    suspend fun deleteOldTasks(cutoffDate: Date) {
        taskDao.deleteOldTasks(cutoffDate)
    }
    
    /**
     * 获取任务总数
     */
    suspend fun getTaskCount(): Int {
        return taskDao.getTaskCount()
    }
    
    /**
     * 根据状态获取任务数量
     */
    suspend fun getTaskCountByStatus(status: TaskStatus): Int {
        return taskDao.getTaskCountByStatus(status)
    }
    
    /**
     * 创建新任务
     */
    suspend fun createTask(
        description: String,
        userInput: String,
        steps: List<com.autoglm.data.model.ActionStep>,
        parameters: Map<String, String> = emptyMap(),
        applicationFlow: List<String> = emptyList()
    ): Task {
        val taskId = generateTaskId()
        val now = Date()
        
        val task = Task(
            id = taskId,
            description = description,
            userInput = userInput,
            steps = steps,
            status = TaskStatus.PENDING,
            createdAt = now,
            updatedAt = now,
            parameters = parameters,
            applicationFlow = applicationFlow
        )
        
        insertTask(task)
        return task
    }
    
    /**
     * 更新任务状态
     */
    suspend fun updateTaskStatus(taskId: String, status: TaskStatus, errorMessage: String? = null) {
        val task = getTaskById(taskId) ?: return
        val updatedTask = task.copy(
            status = status,
            updatedAt = Date(),
            completedAt = if (status == TaskStatus.COMPLETED) Date() else task.completedAt,
            errorMessage = errorMessage
        )
        updateTask(updatedTask)
    }
    
    private fun generateTaskId(): String {
        return "task_${System.currentTimeMillis()}_${(1000..9999).random()}"
    }
}

/**
 * 扩展函数：TaskEntity转Task
 */
private fun TaskEntity.toTask(): Task {
    return Task(
        id = id,
        description = description,
        userInput = userInput,
        steps = steps,
        status = status,
        createdAt = createdAt,
        updatedAt = updatedAt,
        completedAt = completedAt,
        errorMessage = errorMessage,
        parameters = parameters,
        applicationFlow = applicationFlow
    )
}

/**
 * 扩展函数：Task转TaskEntity
 */
private fun Task.toEntity(): TaskEntity {
    return TaskEntity(
        id = id,
        description = description,
        userInput = userInput,
        steps = steps,
        status = status,
        createdAt = createdAt,
        updatedAt = updatedAt,
        completedAt = completedAt,
        errorMessage = errorMessage,
        parameters = parameters,
        applicationFlow = applicationFlow
    )
}
